﻿using Kxx_Common;
using Kxx_Common.INI;
using Kxx_Common.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Reflection.Metadata;
using Kxx_Log.Log;

namespace DNS_BackGroundService
{
    internal class LogSocketServer
    {
        private int noticeTime = 3 * 1000;  //通知时间ms

        TcpServer tcpServer;
        public LogSocketServer()
        {
            Init();
        }

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            #region 端口处理
            INIFile ini = new INIFile(AppDomain.CurrentDomain.BaseDirectory + @"bascconfig.ini");
            int port = ini.IniReadValue("DNS", "SPort").ToInt();
            port = GetPort(port);
            ini.IniWriteValue("DNS", "SPort", port.ToString());
            #endregion

            #region 通讯服务启动
            tcpServer = new TcpServer();
            tcpServer.OpenServer(port);
            #endregion

            LogTask();
        }
        #endregion

        #region 端口获取
        /// <summary>
        /// 获取未被占用的端口（50000 - 60000）
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        private int GetPort(int port = -1)
        {
            Random random= new Random();
            while (port == -1 || PortInUse(port))
            {
                port = random.Next(50000, 60000);

                Thread.Sleep(10);
            }

            return port;
        }

        /// <summary>
        /// 端口是否在使用
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }

            return inUse;  // 返回true说明端口被占用
        }
        #endregion

        #region 任务
        /// <summary>
        /// 日志任务
        /// </summary>
        private void LogTask()
        {
            new Task(() => {
                while (true)
                {
                    try
                    {
                        //存在客户端链接时，发送日志信息
                        if (tcpServer.dic_ClientSocket.Count > 0 && DNSLog.LogList.Count > 0)
                        {
                            List<LogModel> list = DNSLog.LogList.ToList();
                            DNSLog.LogList.Clear();

                            foreach (LogModel log in list)
                            {
                                log.LogSource = "DNSBackGroundService服务：" + log.LogSource;
                            }

                            byte[] data = Encoding.UTF8.GetBytes(ConvertJson.SerializeObject(list));
                            tcpServer.SendData(data);
                        }
                    }
                    catch (Exception ex) { DNSLog.LogAdd(LogType.Error, "DNSBackGroundService服务：日志任务", $"Error：{ex.Message}"); }

                    Thread.Sleep(noticeTime);
                }
            }).Start();
        }
        #endregion
    }
}
